﻿namespace MapleRock.P2PEmulator.RGR
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  public static class Stats
  {
    public static double Dispersion(double[] values)
    {
      double expectation = Stats.Expectation(values);

      double[] dispersion= new double[values.Length];
      for (var i = 0; i < values.Length; ++i)
      {
        dispersion[i] = Math.Abs(values[i] - expectation);
      }

      return dispersion.Sum() / dispersion.Length;
    }

    public static double Expectation(double[] values)
    {
      return values.Sum() / values.Length;
    }

    public static double Deviation(double value, double[] values)
    {
      double[] deviation = new double[values.Length];
      for (var i = 0; i < values.Length; ++i)
      {
        deviation[i] = Math.Abs(values[i] - value);
      }

      return deviation.Sum() / deviation.Length;
    }

    public static double DeviationExpectation(double[] values)
    {
      double[] deviation = new double[values.Length];
      for (var i = 0; i < values.Length; ++i)
      {
        deviation[i] = Stats.Deviation(values[i], values);
      }

      return deviation.Sum() / deviation.Length;
    }

    public static List<double> DeviationExpectationFilter(double[] values, double sigma)
    {
      var result = new List<double>();

      var deviationExpectation = Stats.DeviationExpectation(values);
      foreach (var v in values)
      {
        var deviation = Stats.Deviation(v, values);
        var filterPassed = Math.Abs(deviation - deviationExpectation) <= sigma;
        if (filterPassed)
        {
          result.Add(v);
        }
      }

      return result;
    }
  }
}
